package net.oschina.git.utils;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.eclipse.swt.widgets.Shell;

public class HttpUtil {
	private  static CloseableHttpClient httpclient = null;
	private  static HashMap<String,String> header = null;
	static {
		if(httpclient==null){
			RequestConfig.Builder requestBuilder = RequestConfig.custom();
			requestBuilder = requestBuilder.setConnectTimeout(5000);
			requestBuilder = requestBuilder.setConnectionRequestTimeout(5000);

			HttpClientBuilder builder = HttpClientBuilder.create();     
			builder.setDefaultRequestConfig(requestBuilder.build());
			httpclient = builder.build();
		}
		if(header == null){
			header = new HashMap<String,String>();
			header.put("Content-Type", "application/x-www-form-urlencoded");
			header.put("User-Agent", "CC/1.0-$EC");
		}
	}
	public  static String post(String url,List<NameValuePair> params,Shell shell) throws ConnectTimeoutException, ClientProtocolException, IOException{
		HttpPost hp = new HttpPost(url); 
		HttpResponse response = null;
		for(String st:header.keySet()){
			hp.setHeader(st, header.get(st));
		}
		HttpEntity entity = new UrlEncodedFormEntity(params, "utf-8");  
        hp.setEntity(entity);  
		response = httpclient.execute(hp);
        String responseHtml = EntityUtils.toString(response.getEntity());
		return responseHtml;
	}
	public static String get(String url) throws ClientProtocolException, IOException{
		HttpGet hg = new HttpGet(url);
		for(String st:header.keySet()){
			hg.setHeader(st, header.get(st));
		}
		HttpResponse response = httpclient.execute(hg);  
        String responseHtml = EntityUtils.toString(response.getEntity()); 
        return responseHtml;
	}
}
